import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:demo/empUtils/EMPColorUtils.dart';
import 'package:demo/empUtils/EMPLayoutUtils.dart';
import 'package:demo/empUtils/EMPImageUtils.dart';
import 'package:demo/empUtils/EMPObjectUtil.dart';

//对应参数不传控件则不显示

enum CustomCellType {
  EMPeDefaultCell, //左文本，右文本,右侧图片
  EMPAvatarTitleCell, //左侧头像,头像右侧一个标题，一个副标题
  EMPAvatarTitleIconCell, //左侧头像,头像右侧一个标题，两个副标题，标题右侧一个图片
  EMPTitleSwitchCell, //左文本,右开关
  EMPTitleBtnCell, //左文本,右按钮

  EMPSelAvatarTitleCell, //左侧头像,头像右侧一个标题，一个副标题 (有复选框)
}

class EMPCustomCell extends StatefulWidget {
  final CustomCellType cellTpe;
  final VoidCallback onTap; //cell点击回调
  final String title; //主标题

  final String? subtitle; //副标题
  final String? subtitleTwo; //二级副标题
  final String? rightTitle; //右侧文本
  final String? avatarIcon; //头像
  final String? arrowIcon;
  final bool? showBotmLine; //显示底部下划线，默认不显示
  final bool? isLineFeed; //是否可以换行,默认换行
  final String? richTitle; //需要变色文本
  final String? richColor; //变色文本颜色
  final bool? switchValue;
  final Function(bool)? onValueChanged; //开关回调
  final Function()? clickBtn; //按钮回调
  final bool? isSel;//是否选中

  EMPCustomCell(this.cellTpe, this.title, this.onTap,
      {this.subtitle,
        this.rightTitle,
        this.avatarIcon,
        this.arrowIcon,
        this.subtitleTwo,
        this.switchValue,
        this.onValueChanged,
        this.clickBtn,
        this.showBotmLine,
        this.richTitle,
        this.richColor,
        this.isSel,
        this.isLineFeed = true});

  @override
  _EMPCustomCellState createState() => _EMPCustomCellState();
}

class _EMPCustomCellState extends State<EMPCustomCell> {
  bool _switchValue = false;

  @override
  void initState() {
    //被创建时第一次会调用，初始化
    super.initState();
    _switchValue = widget.switchValue ?? false; //为空时默认false
  }

  @override
  Widget build(BuildContext context) {
    if (widget.cellTpe == CustomCellType.EMPeDefaultCell) {
      return DefaultCell();
    } else if (widget.cellTpe == CustomCellType.EMPAvatarTitleCell || widget.cellTpe == CustomCellType.EMPSelAvatarTitleCell) {
      return AvatarlTitleCell();
    } else if (widget.cellTpe == CustomCellType.EMPAvatarTitleIconCell ) {
      return AvatarlTitleIconCell();
    } else if (widget.cellTpe == CustomCellType.EMPTitleSwitchCell) {
      return TitleSwitchCell();
    } else if (widget.cellTpe == CustomCellType.EMPTitleBtnCell) {
      return TitleBtnCell();
    }

    return Container();
  }

  Widget TitleBtnCell() {
    return Container(
      padding: EdgeInsets.only(left: 16, right: 16, top: 11, bottom: 11),
      decoration: widget.showBotmLine == true
          ? BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Colors.grey.shade300),
        ),
      )
          : null,
      child: Row(
        children: [
          Container(
            constraints: BoxConstraints(maxWidth: EMPLayout().screenWidth / 2),
            child: buildChoseText(widget.title, 17, EMPColor.text_black, FontWeight.normal,
                richTitle: widget.richTitle, richHexColor: widget.richColor),
          ),
          Expanded(
              child: Align(
                  alignment: Alignment.centerRight,
                  child: TextButton(
                    onPressed: () {
                      widget.clickBtn != null ? widget.clickBtn!() : null;
                    },
                    style: ButtonStyle(
                      overlayColor: MaterialStateProperty.resolveWith<Color?>((states) {
                        return Colors.transparent; // 设置水波纹颜色为透明，不显示水波纹效果
                      }),
                    ),
                    child: buildChoseText(widget.title, 15, Colors.blueAccent, FontWeight.normal,
                        richTitle: widget.richTitle, richHexColor: widget.richColor),
                  ))),
        ],
      ),
    );
  }

  Widget TitleSwitchCell() {
    return Container(
      padding: EdgeInsets.only(left: 16, right: 16, top: 11, bottom: 11),
      decoration: widget.showBotmLine == true
          ? BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Colors.grey.shade300),
        ),
      )
          : null,
      child: Row(
        children: [
          Container(
            constraints: BoxConstraints(maxWidth: EMPLayout().screenWidth / 2),
            child: buildChoseText(widget.title, 17, EMPColor.text_black, FontWeight.normal,
                richTitle: widget.richTitle, richHexColor: widget.richColor),
          ),
          Expanded(
              child: Align(
                alignment: Alignment.centerRight,
                child: Switch(
                  value: _switchValue,
                  onChanged: (value) {
                    setState(() {
                      _switchValue = value;
                    });
                    widget.onValueChanged != null ? widget.onValueChanged!(value) : null;
                  },
                ),
              )),
        ],
      ),
    );
  }

  Widget AvatarlTitleIconCell() {
    return GestureDetector(
      onTap: widget.onTap,
      child: Container(
        padding: EdgeInsets.only(left: 16, right: 16, top: 11, bottom: 11),
        decoration: widget.showBotmLine == true
            ? BoxDecoration(
          border: Border(
            bottom: BorderSide(color: Colors.grey.shade300),
          ),
        )
            : null,
        child: Row(
          children: [
            buildImage(widget.avatarIcon!, 56, 56),
            Expanded(
              child: Padding(
                padding: EdgeInsets.only(left: 15),
                child: Column(
                  children: [
                    Row(
                      children: [
                        buildChoseText(widget.title, 24, Colors.black, FontWeight.w600,
                            isFlex: true),
                        EMPLayout.hGap10,
                        buildImage(widget.arrowIcon!, 18, 18),
                      ],
                    ),
                    EMPObjectUtil.isEmpty(widget.subtitle)
                        ? EMPLayout.empty
                        : Padding(
                      padding: EdgeInsets.only(top: 5),
                      child: buildChoseText(
                          widget.subtitle ?? '', 14, EMPColor.text_gay, FontWeight.normal,
                          richTitle: widget.richTitle, richHexColor: widget.richColor),
                    ),
                    EMPObjectUtil.isEmpty(widget.subtitleTwo)
                        ? EMPLayout.empty
                        : Padding(
                      padding: EdgeInsets.only(top: 5),
                      child: buildChoseText(
                          widget.subtitleTwo ?? '', 14, EMPColor.text_gay, FontWeight.normal,
                          richTitle: widget.richTitle, richHexColor: widget.richColor),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget AvatarlTitleCell() {
    return GestureDetector(
      onTap: widget.onTap,
      child: Container(
        padding: EdgeInsets.only(left: 16, right: 16, top: 11, bottom: 11),
        decoration: widget.showBotmLine == true
            ? BoxDecoration(
          border: Border(
            bottom: BorderSide(color: Colors.grey.shade300),
          ),
        )
            : null,
        child: Row(
          children: [
            widget.cellTpe == CustomCellType.EMPSelAvatarTitleCell ? Image(
              image: EMPImageUtils.getAssetImage('other/setting'),
              width: 15,
            ) : Container(),
            buildImage(widget.avatarIcon!, 46, 46),
            // EMPLayout.hGap15,
            Expanded(
              child: Padding(
                padding: EdgeInsets.only(left: 15.0),
                child: Column(
                  children: [
                    Align(
                      alignment: Alignment.centerLeft,
                      child: buildChoseText(
                          widget.title, 17, EMPColor.text_black, FontWeight.normal,
                          richTitle: widget.richTitle, richHexColor: widget.richColor),
                    ),
                    EMPObjectUtil.isEmpty(widget.subtitle)
                        ? EMPLayout.empty
                        : Padding(
                      padding: EdgeInsets.only(top: 2),
                      child: buildChoseText(
                          widget.subtitle ?? '', 15, EMPColor.text_gay, FontWeight.normal,
                          richTitle: widget.richTitle, richHexColor: widget.richColor),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget DefaultCell() {
    return GestureDetector(
      onTap: widget.onTap,
      child: Container(
        padding: EdgeInsets.all(16.0),
        decoration: widget.showBotmLine == true
            ? BoxDecoration(
          border: Border(
            bottom: BorderSide(color: Colors.grey.shade300),
          ),
        )
            : null,
        child: Row(
          children: [
            Container(
              constraints: BoxConstraints(maxWidth: EMPLayout().screenWidth / 2),
              child: buildChoseText(widget.title, 17, EMPColor.text_black, FontWeight.normal,
                  richTitle: widget.richTitle, richHexColor: widget.richColor),
            ),
            Expanded(
              child: Align(
                alignment: Alignment.centerRight,
                child: Padding(
                  padding: EdgeInsets.only(left: 20.0),
                  child:
                  buildChoseText(widget.rightTitle ?? '', 15, EMPColor.text_gay, FontWeight.normal,
                      richTitle: widget.richTitle, richHexColor: widget.richColor),
                ),
              ),
            ),
            EMPObjectUtil.isEmpty(widget.arrowIcon)
                ? EMPLayout.empty
                : Padding(
              padding: EdgeInsets.only(left: 10.0),
              child: buildImage(widget.arrowIcon!, 15, 15),
            ), //
          ],
        ),
      ),
    );
  }

  Widget buildText(String title, double font, Color color, FontWeight fontStyle) {
    return Text(
      textAlign: TextAlign.left, // 设置文字居左
      softWrap: true, // 开启自动换行 默认开启
      title,
      style: TextStyle(
        fontSize: font,
        fontWeight: fontStyle,
        color: color,
        // 溢出ellipsis省略号，可见部分不被截断visible，clip截断(如果设置ellipsis，即使softWrap为true也无法换行)
        overflow: widget.isLineFeed == true ? TextOverflow.visible : TextOverflow.ellipsis,
      ),
    );
  }

  Widget buildImage(String imageStr, double width, double height) {
    return Image(
      image: EMPImageUtils.getAssetImage(imageStr),
      width: width,
      height: height,
      fit: BoxFit.contain, // 图片适应方式
    );
  }

  Widget buildChoseText(String title, double font, Color color, FontWeight fontStyle,
      {String? richTitle, String? richHexColor, bool isFlex = false}) {
    if (isFlex == true) {
      return Flexible(
        //自适应，类似iOS相对约束
        child: EMPObjectUtil.isEmpty(richTitle)
            ? buildText(title, font, color, fontStyle)
            : buildRichText(title, font, color, fontStyle,
            richTitle: richTitle, richHexColor: richHexColor),
      );
    } else {
      return EMPObjectUtil.isEmpty(richTitle)
          ? buildText(title, font, color, fontStyle)
          : buildRichText(title, font, color, fontStyle,
          richTitle: richTitle, richHexColor: richHexColor);
    }
  }

  Widget buildRichText(String title, double font, Color color, FontWeight fontStyle,
      {String? richTitle, String? richHexColor}) {
    // 正则表达式匹配所有的 richTitle 字符串
    RegExp regex = RegExp(richTitle!);
    Iterable<RegExpMatch> matches = regex.allMatches(title);

    // 富文本
    List<TextSpan> textSpans = [];
    int currentIndex = 0;
    for (RegExpMatch match in matches) {
      // 添加匹配之前的文本
      if (match.start > currentIndex) {
        textSpans.add(
          TextSpan(
            text: title.substring(currentIndex, match.start),
            style: TextStyle(
              fontSize: font,
              fontWeight: fontStyle,
              color: color,
              overflow: widget.isLineFeed == true ? TextOverflow.visible : TextOverflow.ellipsis,
            ),
          ),
        );
      }

      // 添加变色文本
      textSpans.add(
        TextSpan(
          text: match.group(0),
          style: TextStyle(
            fontSize: font,
            color: EMPObjectUtil.isEmpty(richHexColor) ? Colors.red : Color(
                int.parse('0xFF$richHexColor')),
            fontWeight: fontStyle,
          ),
        ),
      );

      currentIndex = match.end;
    }

    // 添加最后一个匹配之后的文本
    if (currentIndex < title.length) {
      textSpans.add(
        TextSpan(
          text: title.substring(currentIndex),
          style: TextStyle(
            fontSize: font,
            fontWeight: fontStyle,
            color: color,
            overflow: widget.isLineFeed == true ? TextOverflow.visible : TextOverflow.ellipsis,
          ),
        ),
      );
    }

    return Text.rich(
      TextSpan(children: textSpans),
    );
  }
}

// 当参数写在大括号外面时候是必选参数，相对应cell调用下面示例
// EMPCustomCell(this.cellTpe, this.title, this.onTap,
//     {
//       this.subtitle,
//       this.rightTitle,
//       this.avatarIcon,
//       this.arrowIcon
//     });
//
// return EMPCustomCell(
// CustomCellType.EMPAvatarCell,
// 'CelltleSubtitleCelltleSubtitle $index',
// () {
//
// },
// arrowIcon: 'other/ic_arrow_right',
// avatarIcon: 'other/ic_arrow_right',
// subtitle: 'SubtitleSubtitleSubtitletleSubtitletleSubtitle $index',
// );
//
// 当参数都在大括号里面时候，想增加必选参数要用required修饰，相对应cell调用下面示例
// EMPCustomCell(
// {
//   required this.cellTpe,
// required this.title,
// required this.onTap,
// this.subtitle,
// this.rightTitle,
// this.avatarIcon,
// this.arrowIcon
// });
//
// return EMPCustomCell(
//   title: 'CelltleSubtitleCelltleSubtitle $index',
//   subtitle: 'SubtitleSubtitleSubtitletleSubtitletleSubtitle $index',
//   cellTpe: CustomCellType.EMPAvatarCell,// EMPeDefaultCell
//   avatarIcon: 'other/ic_arrow_right',
//   arrowIcon: 'other/ic_arrow_right',
//   onTap: () {
//     print('Cell $index 被点击了');
//   },
// );
